import os

from django import http
from django.conf import settings
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.orders.models import OrderInfo
from alipay import AliPay

from apps.payment.models import Payment
from utils.response_code import RETCODE




class PayMentStatusView(View):
    def get(self,request):
        #接收 解析sign
        query_dict = request.GET
        data = query_dict.dict()
        signature = query_dict.pop("sign")

        #支付宝校验

        #支付宝对象
        alipay= AliPay(
            appid = settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG,
        )
        #verify校验
        success = alipay.verify(data,signature)
        if success:
        # 取出参数  存入数据库
            order_id = data.get("out_trade_no")
            trade_no = data.get("trade_no")
            #保存Payment模型类数据
            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_no,
            )
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM["UNCOMMENT"])
            context = {
                "trade_id":trade_no
            }
            return render(request,"pay_success.html",context)
        # 修改订单状态
        else:
            return http.HttpResponseForbidden("非法请求")


class PayMentView(View):
    def get(self,request,order_id):
        #1.接收参数
        #2.验证订单是否存在
        user = request.user
        try:
            order = OrderInfo.objects.get(order_id=order_id,user=user,status=OrderInfo.ORDER_STATUS_ENUM["UNPAID"])
        except OrderInfo.DoesNotExist:
            return http.HttpResponseForbidden("订单不存在")
        #3.验证支付宝的对象--创建支付宝对象
        alipay = AliPay(
            appid = settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),"keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),"keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG,
        )
        #4.加密order_id,subject,total_amount参数  支付宝
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城：{}".format(order_id),
            return_url=settings.ALIPAY_RETURN_URL,

        )
        #5.返回支付宝的登陆网址--拼接网址--网关 +加密完string
        alipay_url = settings.ALIPAY_URL +"?"+ order_string
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK","alipay_url":alipay_url})

